package com.zan.seckillservice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zan.seckillservice.domain.Goods;
import com.zan.seckillservice.domain.OrderRecords;
import com.zan.seckillservice.mapper.OrderRecordsMapper;
import com.zan.seckillservice.service.GoodsService;
import com.zan.seckillservice.mapper.GoodsMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Zan421
 * @description 针对表【goods】的数据库操作Service实现
 * @createDate 2024-09-02 19:01:50
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private OrderRecordsMapper orderRecordsMapper;

    /**
     * 扣减库存 -1
     * 写订单表
     *
     * @param userId
     * @param goodsId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void realSeckill(Integer userId, Integer goodsId) {
//        synchronized (this) { // 单例对象才能锁
            Goods goods = goodsMapper.selectById(goodsId);
            int finalStock = goods.getStocks() - 1;
            if (finalStock < 0) {
                throw new RuntimeException("商品id:" + goodsId + "库存不足, id为:" + userId);
            }
            goods.setStocks(finalStock);
            goods.setUpdateTime(new Date());
            int i = goodsMapper.updateById(goods);
            if (i > 0) {
                OrderRecords orderRecords = new OrderRecords();
                orderRecords.setUserId(userId);
                orderRecords.setGoodsId(goodsId);
                orderRecords.setCreateTime(new Date());
                orderRecordsMapper.insert(orderRecords);
            }
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void realSeckill2(Integer userId, Integer goodsId) {
        // 这里使用的锁是MySQL的行锁来控制的，通过MySQL来控制锁，都改同一行
        // 但是一旦并发量大就不好，因为MySQL的压力太大了
        // update goods set stocks = stocks - 1 where id = #{goodsId} and stock - 1 >= 0
        int i = goodsMapper.updateStore(goodsId);
        if (i > 0) {
            OrderRecords orderRecords = new OrderRecords();
            orderRecords.setUserId(userId);
            orderRecords.setGoodsId(goodsId);
            orderRecords.setCreateTime(new Date());
            orderRecordsMapper.insert(orderRecords);
        }
    }
}




